package com.hsl.housaileibot001.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsl.housaileibot001.mapper.InterviewQuestionMapper;
import com.hsl.housaileibot001.model.InterviewQuestion;
import com.hsl.housaileibot001.model.dto.QuestionImportDTO;
import com.hsl.housaileibot001.model.vo.TagVO;
import com.hsl.housaileibot001.service.InterviewQuestionService;
import com.hsl.housaileibot001.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 面试题目服务实现类
 */
@Slf4j
@Service
public class InterviewQuestionServiceImpl extends ServiceImpl<InterviewQuestionMapper, InterviewQuestion> implements InterviewQuestionService {

    @Override
    public int batchImport(List<InterviewQuestion> questions) {
        if (questions == null || questions.isEmpty()) {
            return 0;
        }

        // 批量保存
        boolean success = saveBatch(questions);
        return success ? questions.size() : 0;
    }

    @Override
    public String importFromExcel(MultipartFile file) {
        try {
            // 验证文件
            if (!ExcelUtil.isExcelFile(file)) {
                return "文件格式不正确，请上传Excel文件（.xlsx或.xls）";
            }

            // 读取Excel文件
            List<InterviewQuestion> questions = ExcelUtil.importExcel(file, InterviewQuestion.class);

            if (questions == null || questions.isEmpty()) {
                return "Excel文件中没有有效数据";
            }

            // 批量导入
            int successCount = batchImport(questions);

            return String.format("导入成功！共处理 %d 条数据，成功导入 %d 条数据", questions.size(), successCount);

        } catch (IOException e) {
            log.error("Excel文件导入失败", e);
            return "文件读取失败：" + e.getMessage();
        } catch (Exception e) {
            log.error("Excel文件导入过程中发生错误", e);
            return "导入过程中发生错误：" + e.getMessage();
        }
    }

    @Override
    public int batchImportFromDTO(List<QuestionImportDTO> importDTOs) {
        if (importDTOs == null || importDTOs.isEmpty()) {
            return 0;
        }

        // 将DTO转换为实体对象
        List<InterviewQuestion> questions = importDTOs.stream()
                .map(this::convertDTOToEntity)
                .collect(Collectors.toList());

        // 批量保存
        boolean success = saveBatch(questions);
        return success ? questions.size() : 0;
    }

    @Override
    public String importFromExcelWithDTO(MultipartFile file) {
        try {
            // 验证文件
            if (!ExcelUtil.isExcelFile(file)) {
                return "文件格式不正确，请上传Excel文件（.xlsx或.xls）";
            }

            // 读取Excel文件
            List<QuestionImportDTO> importDTOs = ExcelUtil.importExcel(file, QuestionImportDTO.class);

            if (importDTOs == null || importDTOs.isEmpty()) {
                return "Excel文件中没有有效数据";
            }

            // 批量导入
            int successCount = batchImportFromDTO(importDTOs);

            return String.format("导入成功！共处理 %d 条数据，成功导入 %d 条数据", importDTOs.size(), successCount);

        } catch (IOException e) {
            log.error("Excel文件导入失败", e);
            return "文件读取失败：" + e.getMessage();
        } catch (Exception e) {
            log.error("Excel文件导入过程中发生错误", e);
            return "导入过程中发生错误：" + e.getMessage();
        }
    }

    /**
     * 将DTO转换为实体对象
     *
     * @param dto DTO对象
     * @return 实体对象
     */
    private InterviewQuestion convertDTOToEntity(QuestionImportDTO dto) {
        InterviewQuestion question = new InterviewQuestion();
        question.setTitle(dto.getTitle());
        question.setDifficulty(dto.getDifficulty());
        question.setTags(dto.getTags());
        question.setLink(dto.getLink());

        // 设置来源，如果DTO中没有指定来源，则默认为 mianshiya.com
        String source = dto.getSource();
        if (source == null || source.trim().isEmpty()) {
            source = "mianshiya.com";
        }
        question.setSource(source);

        // 设置默认值
        question.setViewCount(0);
        question.setLikeCount(0);
        question.setCollectCount(0);
        question.setStatus("ACTIVE");
        question.setDeleted(false);
        question.setVersion(1);

        return question;
    }

    @Override
    public void pageWithSearch(Page<InterviewQuestion> page, String title, String tags) {
        LambdaQueryWrapper<InterviewQuestion> queryWrapper = new LambdaQueryWrapper<>();

        // 标题模糊搜索（不区分大小写）
        if (StringUtils.hasText(title)) {
            queryWrapper.apply("LOWER(title) LIKE LOWER({0})", "%" + title + "%");
        }

        // 标签精确匹配（支持多个标签，只要包含任意一个标签即匹配）
        if (StringUtils.hasText(tags)) {
            String[] tagArray = tags.split(",");
            queryWrapper.nested(wrapper -> {
                for (int i = 0; i < tagArray.length; i++) {
                    String tag = tagArray[i].trim();
                    if (i == 0) {
                        wrapper.apply("EXISTS (SELECT 1 FROM unnest(string_to_array(tags, ',')) AS split_tag WHERE TRIM(split_tag) = {0})", tag);
                    } else {
                        wrapper.or(w -> w.apply("EXISTS (SELECT 1 FROM unnest(string_to_array(tags, ',')) AS split_tag WHERE TRIM(split_tag) = {0})", tag));
                    }
                }
            });
        }

        // 添加逻辑删除条件
        queryWrapper.eq(InterviewQuestion::getDeleted, false);

        // 分页查询
        page(page, queryWrapper);
    }

    @Override
    public IPage<TagVO> pageTagList(Page<TagVO> page) {
        return baseMapper.pageTagList(page);
    }

    @Override
    public boolean updateStatus(Long id, String status) {
        if (id == null || !StringUtils.hasText(status)) {
            return false;
        }
        InterviewQuestion entity = new InterviewQuestion();
        entity.setId(id);
        entity.setStatus(status);
        return updateById(entity);
    }
}